package cn.openea.perpartner.componet.aspect;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.common.core.utils.ServletUtils;
import cn.openea.perpartner.common.core.utils.http.HttpHelper;
import cn.openea.perpartner.common.core.utils.spring.SpringUtils;
import cn.openea.perpartner.componet.annotation.ChainLog;
import cn.openea.perpartner.componet.handler.ChainProcessor;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.TimerTask;

/**
 * @author Weird077
 * @description TODO
 * @date 2023-03-07 11:00
 */
@Aspect
@Component
public class ChainAspect {
    private static final Logger log = LoggerFactory.getLogger(ChainAspect.class);

    /**
     * 处理完请求后执行
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)")
    public void doAfterReturning(ChainLog controllerLog) {
        handleLog();
    }

    private void handleLog() {
        try {
            String params = HttpHelper.getBodyString(ServletUtils.getRequest());
            AsyncManager.me().execute(recordLog(BeanUtil.beanToMap(params)));
        } catch (Exception exp) {
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }

    }

    public static TimerTask recordLog(final Map<String, Object> params) {
        return new TimerTask() {
            @Override
            public void run() {

                SpringUtils.getBean(ChainProcessor.class).execute(params);
            }
        };
    }


}
